/**
 * @description 路由拦截状态管理，目前两种模式：all模式与intelligence模式，其中partialRoutes是菜单暂未使用
 */
import { defineStore } from 'pinia'
import { local } from '@/utils/storage'
import type { appState, userinfoType } from '@/types/stores/app'
import loginApi from '@/service/api/login'
import { setLocale } from '@/utils/i18n'

export const useAppsStore = defineStore('app', {
  state: (): appState => ({
    token: '',
    userInfo: {},
    permissions: [],
    lang: local.get('lang') || 'zhCN',
  }),
  getters: {
    getLang: (state) => state.lang,
    getToken: (state) => state.token,
    getPermissions: (state) => state.permissions,
    getLoginStatus: (state) => !!state.userInfo?.userId,
    getUserInfo: (state) => state.userInfo as userinfoType,
  },
  actions: {
    setAppLang(lang: App.lang) {
      setLocale(lang)
      local.set('lang', lang)
      this.lang = lang
    },
    /**
     * @description 获取用户信息
     * @returns data
     */
    async doUserInfo(): Promise<userinfoType> {
      const { code, data, msg } = await loginApi.doInfo()
      if (code !== 0) {
        this.signOut()
        throw msg
      }
      this.userInfo = data.sysUser
      this.permissions = data.permissions
      return data
    },
    /**
     * @description 设置token，并且获取用户信息
     * @param token
     * @returns
     */
    async setToken(token: string) {
      local.set(import.meta.env.VITE_TOKEN_LOACTION_NAME, token)
      this.token = token
      return await this.doUserInfo()
    },
    /**
     * @description 登出
     * */
    signOut() {
      local.remove(import.meta.env.VITE_TOKEN_LOACTION_NAME)
      this.token = ''
      this.userInfo = {}
      this.permissions = []
    },
  },
})
